package com.taotao.web.handlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.common.utils.CookieUtils;
import com.taotao.web.bean.User;
import com.taotao.web.service.UserService;
import com.taotao.web.threadlocal.UserThreadLocal;

public class UserLoginHandlerInterceptor implements HandlerInterceptor {
	public static final String COOKIES_NAME="TT_TOKEN";
	@Autowired
	private UserService userService;
//前置(controller方法执行前执行)
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//清空线程
		UserThreadLocal.set(null);
		String token = CookieUtils.getCookieValue(request, COOKIES_NAME);
		String loginUrl = this.userService.SSO_TAOTAO_BASE_URL+"/user/login.html";
		if (StringUtils.isEmpty(token)) {
			
			//为空 未登录,跳转登录页面
			response.sendRedirect(loginUrl);
			return false; 
		}
		//未登录 调用sso来查询接口查询数据是否处于登录状态
		User user = this.userService.queryByUserToken(token);
		if (user==null) {
			//登录超时
			response.sendRedirect(loginUrl);
			return false;
		}
		//登录成功,绑定线程
		UserThreadLocal.set(user);
		return true;
	}
//后置
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}
//完成(视图渲染完成)
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
	}

}
